<template>
  <div class="question-management-container">
    <div class="page-header">
      <h2>试题管理</h2>
      <div class="actions">
        <el-button type="primary" @click="handleCreateQuestion">
          <el-icon><Plus /></el-icon>
          添加试题
        </el-button>
        <el-button type="success" @click="showBatchImportDialog">
          <el-icon><Upload /></el-icon>
          批量导入
        </el-button>
      </div>
    </div>
    
    <!-- 搜索区域 -->
    <div class="search-section">
      <h3>搜索试题</h3>
      <div class="search-form">
        <div class="form-item">
          <label>类型：</label>
          <el-select v-model="filters.type" placeholder="所有类型" clearable style="width: 140px">
            <el-option label="所有类型" value="" />
            <el-option label="单选题" value="SINGLE_CHOICE" />
            <el-option label="判断题" value="TRUE_FALSE" />
            <el-option label="填空题" value="FILL_BLANK" />
            <el-option label="简答题" value="SHORT_ANSWER" />
          </el-select>
        </div>
        
        <div class="form-item">
          <label>难度：</label>
          <el-select v-model="filters.difficulty" placeholder="所有难度" clearable style="width: 140px">
            <el-option label="所有难度" value="" />
            <el-option label="难度 1" :value="1" />
            <el-option label="难度 2" :value="2" />
            <el-option label="难度 3" :value="3" />
            <el-option label="难度 4" :value="4" />
            <el-option label="难度 5" :value="5" />
          </el-select>
        </div>
        
        <div class="form-item">
          <label>知识点：</label>
          <el-input v-model="filters.knowledgePoint" placeholder="搜索知识点关键词" clearable style="width: 200px" />
        </div>
        
        <div class="form-item buttons">
          <el-button type="primary" @click="handleFilterChange" :loading="loading">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetFilters">
            <el-icon><RefreshRight /></el-icon>
            重置
          </el-button>
        </div>
      </div>
    </div>
    
    <el-table
      v-loading="loading"
      :data="questions"
      stripe
      border
      style="width: 100%"
      :default-sort="{ prop: 'createTime', order: 'descending' }"
    >
      <el-table-column prop="id" label="ID" width="80" />
      
      <el-table-column prop="type" label="题型" width="100">
        <template #default="scope">
          <el-tag :type="getQuestionTypeTag(scope.row.type)">
            {{ formatQuestionType(scope.row.type) }}
          </el-tag>
        </template>
      </el-table-column>
      
      <el-table-column prop="content" label="题目内容" min-width="250">
        <template #default="scope">
          <div class="question-content">
            {{ truncateText(scope.row.content, 50) }}
          </div>
        </template>
      </el-table-column>
      
      <el-table-column prop="difficulty" label="难度" width="120">
        <template #default="scope">
          <el-rate
            v-model="scope.row.difficulty"
            disabled
            text-color="#ff9900"
            score-template="{value}"
          />
        </template>
      </el-table-column>
      
      <el-table-column prop="score" label="分值" width="80" />
      
      <el-table-column prop="knowledgePoint" label="知识点" width="120">
        <template #default="scope">
          <el-tag type="info" size="small" v-if="scope.row.knowledgePoint">
            {{ scope.row.knowledgePoint }}
          </el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
      
      <el-table-column prop="createTime" label="创建时间" width="180" sortable>
        <template #default="scope">
          {{ formatDateTime(scope.row.createTime) }}
        </template>
      </el-table-column>
      
      <el-table-column label="操作" width="220" fixed="right">
        <template #default="scope">
          <router-link :to="`/questions/${scope.row.id}`">
            <el-button size="small" type="primary">查看</el-button>
          </router-link>
          <el-button 
            size="small" 
            type="warning" 
            @click="handleEdit(scope.row)"
          >
            编辑
          </el-button>
          <el-button 
            size="small" 
            type="danger" 
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <div class="pagination-container">
      <el-pagination
        v-if="total > 0"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :current-page="currentPage"
        @current-change="handlePageChange"
        @size-change="handleSizeChange"
      />
    </div>
    
    <!-- 编辑/创建试题对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑试题' : '创建试题'"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="questionFormRef"
        :model="questionForm"
        :rules="formRules"
        label-position="top"
      >
        <el-form-item label="题型" prop="type">
          <el-select v-model="questionForm.type" placeholder="请选择题型" :disabled="isEdit">
            <el-option label="单选题" value="SINGLE_CHOICE" />
            <el-option label="判断题" value="TRUE_FALSE" />
            <el-option label="填空题" value="FILL_BLANK" />
            <el-option label="简答题" value="SHORT_ANSWER" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="试题内容" prop="content">
          <el-input
            v-model="questionForm.content"
            type="textarea"
            :rows="5"
            placeholder="请输入试题内容"
          />
        </el-form-item>
        
        <el-form-item label="分值" prop="score">
          <el-input-number v-model="questionForm.score" :min="1" :max="100" />
        </el-form-item>
        
        <el-form-item label="难度" prop="difficulty">
          <el-rate
            v-model="questionForm.difficulty"
            :max="5"
            :texts="['极易', '简单', '中等', '困难', '极难']"
            show-text
          />
        </el-form-item>
        
        <el-form-item label="知识点" prop="knowledgePoint">
          <el-input v-model="questionForm.knowledgePoint" placeholder="请输入知识点" />
        </el-form-item>
        
        <!-- 根据不同题型显示不同的选项输入组件 -->
        <template v-if="questionForm.type === 'SINGLE_CHOICE'">
          <el-divider content-position="left">选项</el-divider>
          <div v-for="(option, index) in questionForm.options" :key="index" class="option-form-item">
            <el-input 
              v-model="questionForm.options[index]" 
              placeholder="请输入选项内容" 
              class="option-input"
            >
              <template #prepend>
                <div style="width: 60px; text-align: center;">选项 {{ String.fromCharCode(65 + index) }}</div>
              </template>
            </el-input>
            <el-button 
              type="danger" 
              icon="Delete" 
              circle 
              @click="removeOption(index)"
              :disabled="questionForm.options.length <= 2"
            />
          </div>
          <div class="option-add-btn">
            <el-button type="primary" @click="addOption" :disabled="questionForm.options.length >= 10">添加选项</el-button>
          </div>
          
          <el-divider content-position="left">答案</el-divider>
          <el-form-item prop="answers">
            <el-radio-group v-model="questionForm.answers[0]">
              <el-radio 
                v-for="(option, index) in questionForm.options" 
                :key="index" 
                :value="String.fromCharCode(65 + index)" 
              >
                {{ String.fromCharCode(65 + index) }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </template>
        
        <template v-else-if="questionForm.type === 'TRUE_FALSE'">
          <el-divider content-position="left">答案</el-divider>
          <el-form-item prop="answers">
            <el-radio-group v-model="questionForm.answers[0]">
              <el-radio value="true">正确</el-radio>
              <el-radio value="false">错误</el-radio>
            </el-radio-group>
          </el-form-item>
        </template>
        
        <template v-else-if="questionForm.type === 'FILL_BLANK' || questionForm.type === 'SHORT_ANSWER'">
          <el-divider content-position="left">答案</el-divider>
          <div v-for="(answer, index) in questionForm.answers" :key="index" class="answer-form-item">
            <el-input 
              v-model="questionForm.answers[index]" 
              :type="questionForm.type === 'SHORT_ANSWER' ? 'textarea' : 'text'"
              :rows="questionForm.type === 'SHORT_ANSWER' ? 3 : 1"
              :placeholder="'请输入答案' + (questionForm.answers.length > 1 ? (index + 1) : '')"
              class="answer-input"
            />
            <el-button 
              v-if="questionForm.type === 'FILL_BLANK' && questionForm.answers.length > 1"
              type="danger" 
              icon="Delete" 
              circle 
              @click="removeAnswer(index)"
            />
          </div>
          <div class="answer-add-btn" v-if="questionForm.type === 'FILL_BLANK'">
            <el-button type="primary" @click="addAnswer" :disabled="questionForm.answers.length >= 10">添加答案</el-button>
          </div>
        </template>
        
        <el-divider content-position="left">答案解析</el-divider>
        <el-form-item label="答案解析" prop="explanation">
          <el-input
            v-model="questionForm.explanation"
            type="textarea"
            :rows="3"
            placeholder="请输入答案解析（选填）"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitting">确认</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 批量导入对话框 -->
    <el-dialog
      v-model="batchImportDialogVisible"
      title="批量导入试题"
      width="800px"
    >
      <div class="batch-import-container">
        <div class="batch-import-description">
          <h3>批量导入说明</h3>
          <p>请按照规定的JSON格式输入试题数据，每个试题需包含：题型、内容、分值、难度等信息。</p>
          <p>下方提供了不同题型的JSON示例，可以点击"插入示例"按钮快速导入示例数据。</p>
        </div>
        
        <div class="examples-container">
          <el-tabs type="card">
            <el-tab-pane label="单选题">
              <pre>{{ singleChoiceExample }}</pre>
              <el-button size="small" type="primary" @click="insertExample('SINGLE_CHOICE')">插入示例</el-button>
            </el-tab-pane>
            <el-tab-pane label="判断题">
              <pre>{{ trueFalseExample }}</pre>
              <el-button size="small" type="primary" @click="insertExample('TRUE_FALSE')">插入示例</el-button>
            </el-tab-pane>
            <el-tab-pane label="填空题">
              <pre>{{ fillBlankExample }}</pre>
              <el-button size="small" type="primary" @click="insertExample('FILL_BLANK')">插入示例</el-button>
            </el-tab-pane>
            <el-tab-pane label="简答题">
              <pre>{{ shortAnswerExample }}</pre>
              <el-button size="small" type="primary" @click="insertExample('SHORT_ANSWER')">插入示例</el-button>
            </el-tab-pane>
          </el-tabs>
        </div>
        
        <div class="json-input-container">
          <el-input
            v-model="batchImportJson"
            type="textarea"
            :rows="15"
            placeholder="请输入符合格式的JSON数据"
          />
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="batchImportDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitBatchImport" :loading="batchSubmitting">确认导入</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useStore } from 'vuex'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Upload, Search, RefreshRight } from '@element-plus/icons-vue'

export default {
  name: 'QuestionManagement',
  components: {
    Plus,
    Upload,
    Search,
    RefreshRight
  },
  setup() {
    const store = useStore()
    const questionFormRef = ref(null)
    
    // 试题列表相关数据
    const questions = computed(() => store.getters.allQuestions)
    const total = computed(() => store.state.questions.total)
    const loading = ref(false)
    const currentPage = ref(1)
    const pageSize = ref(10)
    
    // 筛选条件
    const storeFilters = computed(() => store.getters.questionFilters)
    const filters = reactive({
      type: '',
      difficulty: '',
      knowledgePoint: ''
    })
    
    // 对话框相关数据
    const dialogVisible = ref(false)
    const isEdit = ref(false)
    const submitting = ref(false)
    const questionForm = reactive({
      id: null,
      type: 'SINGLE_CHOICE',
      content: '',
      score: 5,
      difficulty: 3,
      knowledgePoint: '',
      options: ['', '', '', ''],
      answers: ['A'],
      explanation: ''
    })
    
    // 批量导入相关数据
    const batchImportDialogVisible = ref(false)
    const batchImportJson = ref('')
    const batchSubmitting = ref(false)
    
    // 表单验证规则
    const formRules = {
      type: [
        { required: true, message: '请选择题型', trigger: 'change' }
      ],
      content: [
        { required: true, message: '请输入试题内容', trigger: 'blur' },
        { min: 2, max: 1000, message: '内容长度应在2-1000个字符之间', trigger: 'blur' }
      ],
      score: [
        { required: true, message: '请设置分值', trigger: 'blur' },
        { type: 'number', min: 1, max: 100, message: '分值应在1-100之间', trigger: 'blur' }
      ],
      difficulty: [
        { required: true, message: '请设置难度', trigger: 'change' },
        { type: 'number', min: 1, max: 5, message: '难度应在1-5之间', trigger: 'change' }
      ],
      answers: [
        { required: true, message: '请设置正确答案', trigger: 'change' }
      ]
    }
    
    // 初始化
    onMounted(() => {
      // 从store中恢复上次的筛选条件
      if (storeFilters.value) {
        filters.type = storeFilters.value.type || ''
        filters.difficulty = storeFilters.value.difficulty || ''
        filters.knowledgePoint = storeFilters.value.knowledgePoint || ''
      }
      
      fetchQuestions()
    })
    
    // 题型变化时，重置选项和答案
    watch(() => questionForm.type, (newType) => {
      if (newType === 'SINGLE_CHOICE') {
        questionForm.options = ['', '', '', '']
        questionForm.answers = ['A']
      } else if (newType === 'TRUE_FALSE') {
        questionForm.options = []
        questionForm.answers = ['true']
      } else if (newType === 'FILL_BLANK' || newType === 'SHORT_ANSWER') {
        questionForm.options = []
        questionForm.answers = ['']
      }
    })
    
    // 获取试题列表
    const fetchQuestions = async () => {
      loading.value = true;
      try {
        // 保存当前过滤器到store
        store.commit('SET_QUESTION_FILTERS', { 
          type: filters.type,
          difficulty: filters.difficulty,
          knowledgePoint: filters.knowledgePoint
        });
        
        // 让store dispatch处理loading状态
        await store.dispatch('fetchQuestions', {
          page: currentPage.value,
          size: pageSize.value,
          type: filters.type,
          difficulty: filters.difficulty,
          knowledgePoint: filters.knowledgePoint.trim() || null,
          handleLoading: false // 告诉action不要处理loading状态
        });
        
        // 如果结果为空且不是第一页，回到第一页
        if (questions.value.length === 0 && currentPage.value > 1) {
          currentPage.value = 1;
          await fetchQuestions();
        }
      } catch (error) {
        console.error('获取试题列表失败:', error);
        ElMessage.error('获取试题列表失败: ' + (error.message || '请稍后重试'));
      } finally {
        loading.value = false;
      }
    }
    
    // 分页处理
    const handlePageChange = (page) => {
      currentPage.value = page
      fetchQuestions()
    }
    
    // 每页条数改变
    const handleSizeChange = (size) => {
      pageSize.value = size
      currentPage.value = 1
      fetchQuestions()
    }
    
    // 处理筛选条件变化
    const handleFilterChange = async () => {
      currentPage.value = 1;
      await fetchQuestions();
    };
    
    // 重置筛选条件
    const resetFilters = () => {
      filters.type = '';
      filters.difficulty = '';
      filters.knowledgePoint = '';
      currentPage.value = 1;
      fetchQuestions();
    };
    
    // 创建试题
    const handleCreateQuestion = () => {
      isEdit.value = false
      resetForm()
      dialogVisible.value = true
    }
    
    // 编辑试题
    const handleEdit = (question) => {
      isEdit.value = true
      
      questionForm.id = question.id
      questionForm.type = question.type
      questionForm.content = question.content
      questionForm.score = question.score
      questionForm.difficulty = question.difficulty
      questionForm.knowledgePoint = question.knowledgePoint || ''
      questionForm.explanation = question.explanation || ''
      
      // 处理选项和答案，确保 answers 是数组
      if (question.type === 'SINGLE_CHOICE') {
        questionForm.options = [...(question.options || ['', '', '', ''])]
        questionForm.answers = [...(question.answers || ['A'])]
      } else if (question.type === 'TRUE_FALSE') {
        questionForm.options = []
        questionForm.answers = [...(question.answers || ['true'])]
      } else {
        questionForm.options = []
        questionForm.answers = [...(question.answers || [])]
      }
      
      dialogVisible.value = true
    }
    
    // 删除试题
    const handleDelete = (question) => {
      ElMessageBox.confirm(
        '确定要删除该试题吗？此操作不可恢复！',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        try {
          const result = await store.dispatch('deleteQuestion', question.id)
          
          if (result.success) {
            ElMessage.success('试题已删除')
            await fetchQuestions()
          } else {
            ElMessage.error(result.message || '删除失败')
          }
        } catch (error) {
          ElMessage.error('删除失败，请重试')
        }
      }).catch(() => {})
    }
    
    // 添加选项
    const addOption = () => {
      questionForm.options.push('')
    }
    
    // 移除选项
    const removeOption = (index) => {
      questionForm.options.splice(index, 1)
      
      // 更新答案，移除被删除选项对应的答案
      const optionLetter = String.fromCharCode(65 + index)
      const answerIndex = questionForm.answers.indexOf(optionLetter)
      if (answerIndex !== -1) {
        questionForm.answers.splice(answerIndex, 1)
      }
      
      // 更新剩余的答案字母
      const newAnswers = []
      for (const answer of questionForm.answers) {
        const answerCode = answer.charCodeAt(0)
        if (answerCode > 65 + index) {
          newAnswers.push(String.fromCharCode(answerCode - 1))
        } else {
          newAnswers.push(answer)
        }
      }
      questionForm.answers = newAnswers
    }
    
    // 添加答案
    const addAnswer = () => {
      questionForm.answers.push('')
    }
    
    // 移除答案
    const removeAnswer = (index) => {
      questionForm.answers.splice(index, 1)
    }
    
    // 提交表单
    const submitForm = async () => {
      if (!questionFormRef.value) {
        ElMessage.error('表单引用不存在')
        return
      }
      
      try {
        await questionFormRef.value.validate()
        
        submitting.value = true
        
        // 准备提交的数据
        const questionData = {
          type: questionForm.type,
          content: questionForm.content.trim(),
          score: questionForm.score,
          difficulty: questionForm.difficulty,
          knowledgePoint: questionForm.knowledgePoint.trim() || null,
          explanation: questionForm.explanation.trim() || null
        }
        
        // 根据题型，正确设置 options 和 answers 数组
        if (questionForm.type === 'SINGLE_CHOICE') {
          questionData.options = questionForm.options.map(opt => opt.trim())
          questionData.answers = [questionForm.answers[0]]
        } else if (questionForm.type === 'TRUE_FALSE') {
          questionData.options = []
          questionData.answers = [questionForm.answers[0]]
        } else {
          questionData.options = []
          questionData.answers = questionForm.answers.map(ans => ans.trim())
        }
        
        let result
        if (isEdit.value) {
          result = await store.dispatch('updateQuestion', {
            id: questionForm.id,
            question: questionData
          })
        } else {
          result = await store.dispatch('createQuestion', questionData)
        }
        
        if (result.success) {
          ElMessage.success(isEdit.value ? '试题更新成功' : '试题创建成功')
          dialogVisible.value = false
          await fetchQuestions()
        } else {
          ElMessage.error(result.message || (isEdit.value ? '更新失败' : '创建失败'))
        }
      } catch (error) {
        console.error('表单验证失败:', error)
        ElMessage.error('表单验证失败，请检查输入')
      } finally {
        submitting.value = false
      }
    }
    
    // 批量导入示例
    const singleChoiceExample = JSON.stringify([{
      content: "中国的首都是哪个城市？",
      type: "SINGLE_CHOICE",
      difficulty: 1,
      score: 5,
      options: ["A. 上海", "B. 北京", "C. 广州", "D. 深圳"],
      answers: ["B"],
      explanation: "中国的首都是北京",
      knowledgePoint: "地理常识"
    }], null, 2)
    
    const trueFalseExample = JSON.stringify([{
      content: "地球是圆的",
      type: "TRUE_FALSE",
      difficulty: 1,
      score: 2,
      options: ["true", "false"],
      answers: ["true"],
      explanation: "地球实际上是一个椭球体",
      knowledgePoint: "地理常识"
    }], null, 2)
    
    const fillBlankExample = JSON.stringify([{
      content: "中国的首都是____。",
      type: "FILL_BLANK",
      difficulty: 1,
      score: 3,
      options: null,
      answers: ["北京"],
      explanation: "中国的首都是北京",
      knowledgePoint: "地理常识"
    }], null, 2)
    
    const shortAnswerExample = JSON.stringify([{
      content: "请简述Java的特点。",
      type: "SHORT_ANSWER",
      difficulty: 4,
      score: 10,
      options: null,
      answers: ["1. 面向对象\n2. 跨平台性\n3. 安全性\n4. 多线程"],
      explanation: "Java的主要特点包括面向对象、跨平台性、安全性和多线程支持等",
      knowledgePoint: "Java基础"
    }], null, 2)
    
    // 显示批量导入对话框
    const showBatchImportDialog = () => {
      batchImportJson.value = ''
      batchImportDialogVisible.value = true
    }
    
    // 插入示例
    const insertExample = (type) => {
      switch (type) {
        case 'SINGLE_CHOICE':
          batchImportJson.value = singleChoiceExample
          break
        case 'TRUE_FALSE':
          batchImportJson.value = trueFalseExample
          break
        case 'FILL_BLANK':
          batchImportJson.value = fillBlankExample
          break
        case 'SHORT_ANSWER':
          batchImportJson.value = shortAnswerExample
          break
      }
    }
    
    // 提交批量导入
    const submitBatchImport = async () => {
      if (!batchImportJson.value.trim()) {
        ElMessage.error('请输入JSON数据')
        return
      }
      
      try {
        batchSubmitting.value = true
        
        // 解析JSON
        const questions = JSON.parse(batchImportJson.value)
        
        if (!Array.isArray(questions) || questions.length === 0) {
          ElMessage.error('JSON格式不正确，应为试题对象数组')
          return
        }
        
        // 提交批量导入
        const result = await store.dispatch('batchImportQuestions', questions)
        
        if (result.success) {
          ElMessage.success(result.message || '批量导入成功')
          batchImportDialogVisible.value = false
          await fetchQuestions()
        } else {
          ElMessage.error(result.message || '批量导入失败')
        }
      } catch (error) {
        console.error('批量导入失败:', error)
        if (error instanceof SyntaxError) {
          ElMessage.error('JSON语法错误: ' + error.message)
        } else {
          ElMessage.error('批量导入失败: ' + error.message)
        }
      } finally {
        batchSubmitting.value = false
      }
    }
    
    // 格式化试题类型
    const formatQuestionType = (type) => {
      const typeMap = {
        'SINGLE_CHOICE': '单选题',
        'TRUE_FALSE': '判断题',
        'FILL_BLANK': '填空题',
        'SHORT_ANSWER': '简答题'
      }
      return typeMap[type] || type
    }
    
    // 获取试题类型标签样式
    const getQuestionTypeTag = (type) => {
      const tagMap = {
        'SINGLE_CHOICE': 'info',
        'TRUE_FALSE': 'success',
        'FILL_BLANK': 'warning',
        'SHORT_ANSWER': 'info'
      }
      return tagMap[type] || ''
    }
    
    // 文本截断
    const truncateText = (text, length) => {
      if (!text) return ''
      if (text.length <= length) return text
      return text.substring(0, length) + '...'
    }
    
    // 格式化日期时间
    const formatDateTime = (dateString) => {
      if (!dateString) return ''
      const date = new Date(dateString)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
    }
    
    // 重置表单
    const resetForm = () => {
      questionForm.id = null
      questionForm.type = 'SINGLE_CHOICE'
      questionForm.content = ''
      questionForm.score = 5
      questionForm.difficulty = 3
      questionForm.knowledgePoint = ''
      questionForm.options = ['', '', '', '']
      questionForm.answers = ['A']
      questionForm.explanation = ''
    }
    
    return {
      questions,
      total,
      loading,
      currentPage,
      pageSize,
      filters,
      dialogVisible,
      isEdit,
      submitting,
      questionForm,
      questionFormRef,
      formRules,
      batchImportDialogVisible,
      batchImportJson,
      batchSubmitting,
      singleChoiceExample,
      trueFalseExample,
      fillBlankExample,
      shortAnswerExample,
      handlePageChange,
      handleSizeChange,
      handleFilterChange,
      handleCreateQuestion,
      handleEdit,
      handleDelete,
      addOption,
      removeOption,
      addAnswer,
      removeAnswer,
      submitForm,
      showBatchImportDialog,
      insertExample,
      submitBatchImport,
      formatQuestionType,
      getQuestionTypeTag,
      truncateText,
      formatDateTime,
      resetFilters
    }
  }
}
</script>

<style scoped>
.question-management-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 1.5rem;
  color: #303133;
}

.actions {
  display: flex;
  align-items: center;
  gap: 15px;
}

/* 新增搜索容器样式 */
.search-section {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  align-items: center;
}

.form-item {
  display: flex;
  align-items: center;
}

.form-item label {
  margin-right: 8px;
  font-weight: 500;
  color: #606266;
}

.form-item.buttons {
  margin-left: auto;
}

.question-content {
  max-height: 60px;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 1.5;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.option-form-item, .answer-form-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.option-input, .answer-input {
  flex: 1;
  margin-right: 10px;
}

.option-add-btn, .answer-add-btn {
  margin-top: 10px;
  margin-bottom: 20px;
}

.batch-import-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.batch-import-description {
  background-color: #f0f9eb;
  padding: 15px;
  border-radius: 4px;
}

.batch-import-description h3 {
  margin-top: 0;
  color: #67c23a;
  font-size: 16px;
}

.examples-container {
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.examples-container pre {
  background-color: #f5f7fa;
  padding: 15px;
  margin: 0;
  border-radius: 4px;
  overflow: auto;
  max-height: 200px;
  font-family: monospace;
}

.json-input-container {
  margin-top: 10px;
}
</style> 